package au.com.bellygoodengine.servlets;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import au.com.bellygoodengine.DataAccessObject.DAOHub;
import au.com.bellygoodengine.DataAccessObject.DAOInterface.IMenuDAO;
import au.com.bellygoodengine.models.Menu;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class PersistMenuServlet extends AbstractServlet {
	
	private static final Logger log = Logger.getLogger(BellyGoodEngineServlet.class.getName());
	
	@Override
	public void process(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String name = req.getParameter("name");
		String price = req.getParameter("price");
		String description = req.getParameter("description");
        log.info("name: " + name);
        log.info("price: " + price);
        log.info("description: " + description);
		
		Menu menu = new Menu();
		menu.setName(name);
		menu.setDescription(description);
		menu.setPrice(Double.parseDouble(price));
		
		IMenuDAO dao = DAOHub.getInstance().ORDERS_DAO;
		dao.persistMenu(menu);
//		dao.persistOrder(menu);
		
		List<Menu> allMenus = dao.getAllMenus();
		JSONArray jsonArray = new JSONArray(allMenus);
		JSONObject jsonObject = new JSONObject(menu);
		jsonObject.remove("class");
		log.info("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" 
				+ jsonObject.toString()
				+ "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
		);
		
		log.info("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" 
				+ jsonArray.toString()
				+ "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
		);
		
//		resp.setContentType("text");
//		resp.getWriter().write(jsonObject.toString());
		resp.sendRedirect("");
	}
}
